import React, { Component, Fragment } from 'react';
import {
  Card,
  Table,
  Popconfirm,
  message,
  Space,
  Button,
  Pagination,
} from 'antd';
import ProTable from '@ant-design/pro-table';
import { SyncOutlined } from '@ant-design/icons';
import { connect } from 'umi';
import UserModal from './components/UserModal';
import { FormValues } from './data';
import { getRemoteList, editRecord, addRecord } from './service';

class index extends Component {
  constructor(props: any) {
    super(props);
    this.state = {
      confirmLoading: false, // 弹窗的loading
      modalVisible: false, // 控制弹窗
      record: {}, // 点击时候编辑的数据
    };
  }

  // todo 点击编辑的时候
  editHandler = (data: Object) => {
    this.setState({
      record: data,
    });
    this.setModalVisible();
  };

  //  todo 开启弹窗
  setModalVisible() {
    this.setState({
      modalVisible: true,
    });
  }

  // todo 关闭弹窗
  closeModalVisible() {
    this.setState({
      record: {},
      modalVisible: false,
    });
  }

  // todo 点击确认弹窗按钮
  onFinish = async (values: FormValues) => {
    const id = 'id' in this.state.record ? this.state.record.id : null;
    if (id) {
      // this.props.edit(id, values);
      this.setState({
        confirmLoading: true,
      });
      const result = await addRecord(values);
      if (result.state === 0) {
        message.success('新增成功');
        this.closeModalVisible();
        this.setState({
          confirmLoading: false,
        });
        this.props.getRemote();
      } else {
        message.error('新增失败');
      }
    } else {
      // this.props.add(values);
      this.setState({
        confirmLoading: true,
      });
      const result = await addRecord(values);
      if (result.state === 0) {
        message.success('编辑成功');
        this.closeModalVisible();
        this.setState({
          confirmLoading: false,
        });
        this.props.getRemote();
      } else {
        message.error('编辑失败');
      }
    }

    this.setState({
      record: {},
      confirmLoading: false,
    });
  };

  // todo 获取数据
  getList = () => {
    this.props.getRemote();
  };

  // todo 点击删除 - 确认
  confirm = (data: FormValues) => {
    this.props.delete(data.id);
  };

  // todo 点击删除 - 取消
  cancel = (e: any) => {
    message.error('取消删除');
  };

  // todo 新增数据
  addData = () => {
    this.setState({
      record: {},
    });
    this.setModalVisible();
  };

  // todo 处理 antdPro 中表格的 request 函数方法, current 是当前页的意思， pageSize是数量
  requestHandler = async ({ pageSize = 5, current = 1 }) => {
    const users = await getRemoteList(pageSize, current);
    return {
      data: this.props.users.length > 0 ? this.props.users : users.data,
      // success: true,
      total: this.props.meta.total ? this.props.meta.total : users.meta,
    };
  };

  // todo  点击分页(后端处理反的缘故，必须把他们的位置互换)
  handelPagination = async (pageSize: number, page?: number) => {
    this.props.getRemote(page, pageSize);
  };

  // todo 改变每页加载的数量
  onShowSizeChange = (current: number, pageSize: number) => {
    console.log(current, pageSize);
  };

  // todo 点击弹窗确认时候的加载按钮
  confirmLoading = () => {};

  // todo jsx 渲染
  render() {
    const columns = [
      {
        title: 'id',
        dataIndex: 'id',
        key: 'id',
        valueType: 'digit', //设置为数字
      },
      {
        title: '名字',
        dataIndex: 'name',
        key: `name`,
        valueType: 'text', // 默认文本
      },
      {
        title: '邮件',
        key: `email`,
        dataIndex: 'email',
        valueType: 'code', // 设置为代码
      },
      {
        title: '创建时间',
        dataIndex: 'create_time',
        key: 'create_time',
        valueType: 'dateTime', // 日期-时间格式
      },
      {
        title: '更新时间',
        dataIndex: 'update_time',
        key: 'update_time',
        valueType: 'dateTime', // 日期-时间格式
      },
      {
        title: '状态',
        key: 'action',
        valueType: 'option',
        render: (text: any, record: Object) => [
          <a
            onClick={() => {
              this.editHandler(record);
            }}>
            编辑
          </a>,
          <Popconfirm
            title='你确定要删除吗?'
            onConfirm={() => {
              this.confirm(record);
            }}
            onCancel={this.cancel}
            okText='确认'
            cancelText='取消'>
            <a>删除</a>
          </Popconfirm>,
        ],
      },
    ];

    const { users, loading, meta } = this.props;

    return (
      <Fragment>
        <Card className='list-table' hoverable>
          {/* 模态框数据 */}
          <UserModal
            closeModalVisible={this.closeModalVisible.bind(this)}
            visible={this.state.modalVisible}
            confirmLoading={this.state.confirmLoading}
            record={JSON.stringify(this.state.record)}
            onFinish={this.onFinish}></UserModal>

          {/* 表格内容 */}
          <ProTable
            rowKey='id'
            headerTitle='案例表格'
            pagination={false} //关闭默认分页
            columns={columns}
            dataSource={users}
            search={false} // 关闭顶部的搜索区域
            // request={this.requestHandler}
            options={{
              reload: () => {
                this.props.getRemote(5, 1);
              },
            }}
            toolBarRender={() => [
              <Button onClick={this.addData} type='primary'>
                新增数据
              </Button>,
              <Button
                onClick={this.getList}
                icon={<SyncOutlined />}
                style={{
                  marginLeft: '10px',
                }}>
                原始调用
              </Button>,
            ]}
            loading={loading}></ProTable>

          {/* 分页 */}
          <Pagination
            showSizeChanger
            onShowSizeChange={this.onShowSizeChange}
            className={'list-Pagination'}
            total={meta.total}
            current={meta.page}
            showTotal={total => `总共有 ${total} 个数据`}
            onChange={this.handelPagination}
            defaultPageSize={5}
            defaultCurrent={1}
          />
        </Card>
      </Fragment>
    );
  }
}

const mapStateToProps = (state: any) => {
  return {
    meta: state.users.meta, //后端返回的page和per_page处理是错误的，它弄反了
    users: state.users.data,
    loading: state.loading.models.users,
  };
};

// todo 需要 dispatch 的方法写这里
const mapDispatchToProps = (dispatch: any) => {
  return {
    // todo 获取数据
    getRemote(per_page = 5, page = 1) {
      // * 此时派发需要确认 effects，所以加上对应 effects 的 namespace
      dispatch({
        type: 'users/getRemote',
        payload: {
          per_page,
          page,
        },
      });
    },

    // todo 编辑时候派发的函数
    edit(id: Number | String, values: any) {
      values.id = id;
      dispatch({
        type: 'users/edit',
        payload: values,
      });
    },

    // todo 新增数据
    add(values: Object) {
      dispatch({
        type: 'users/add',
        payload: values,
      });
    },

    // todo 删除时候派发的函数
    delete(id: Number | String) {
      dispatch({
        type: 'users/delete',
        payload: { id },
      });
    },
  };
};

// todo 使用 umi 提供的 connect 将功能函数注入 redux
export default connect(mapStateToProps, mapDispatchToProps)(index);
